package com.dragonsoftbravo.sqlbuilder.sql.update;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.dragonsoftbravo.sqlbuilder.SqlContext;
import com.dragonsoftbravo.sqlbuilder.dao.SqlBuilder;
import com.dragonsoftbravo.sqlbuilder.sql.ArgPair;

public class SqlUpdate implements Update {
	StringBuilder sqlBuilder = new StringBuilder();
	SqlBuilder dao;

	public SqlUpdate(SqlBuilder dao) {
		this.dao = dao;
	}

	private UpdateConst update(Object[] args) {
		sqlBuilder.append("UPDATE " + SqlContext.getTable(dao.getTable()) + " SET");
		for (int i = 0; i < args.length; i += 2) {
			sqlBuilder.append(" ").append(SqlContext.getColumn(String.valueOf(args[i]))).append("=").append(SqlContext.getSqlValue(args[i + 1])).append(",");
		}
		sqlBuilder.delete(sqlBuilder.length() - 1, sqlBuilder.length());
		return new SqlUpdateConst(sqlBuilder);
	}

	@Override
	public UpdateConst update(Map<String, Object> args) {
		if (args == null || args.size() < 1) {
			throw new IllegalArgumentException("update args shoud not be null or empty ! ");
		}
		List<Object> objList = new ArrayList<>();
		for (String whereArg : args.keySet()) {
			objList.add(whereArg);
			objList.add(args.get(whereArg));
		}
		return update(objList.toArray());
	}

	@Override
	public UpdateConst update(ArgPair argPair) {
		return update(argPair.argPairMap);
	}
}
